package BehaviorModel.interpreterModel;

import java.util.HashMap;
import java.util.Stack;

/**
 * 功能描述: 上下文
 * 2024/05/13
 * <p>
 * ZhangYi
 */
public class Calculator {
    private AExpression expression;

    /**
     * 功能描述: 计算的表达式 a+b-c+f
     *
     * @param expStr
     * @return
     */
    public Calculator(String expStr) {
        Stack<AExpression> expressions = new Stack<AExpression>();
        char[] chars = expStr.toCharArray();

        for (int index = 0; index < chars.length; index++) {
            switch (chars[index]){
                case '+':
                    AExpression addExp = new AddExpression(expressions.pop(),new VarExpression(String.valueOf(chars[++index])));
                    expressions.push(addExp);
                    break;
                case '-':
                    AExpression subExp = new SubExpression(expressions.pop(),new VarExpression(String.valueOf(chars[++index])));
                    expressions.push(subExp);
                    break;
                default:
                    expressions.push(new VarExpression(String.valueOf(chars[index])));
            }
        }
        this.expression = expressions.pop();
    }

    /**
     * 功能描述: 运行，计算表达式中的变量值 a=13,b=14,c=15
     *
     * @param hashMap
     * @return int
     */
    public int run(HashMap<String,Integer> hashMap) {
        return this.expression.interpret(hashMap);
    }
}
